//
//  UIImageViewWebExt.swift
//  qiubai
//
//  Created by Qingke on 16/5/27.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import Foundation
import UIKit

extension UIImageView {
    func setWedImage(urlString: String, placeHorderImage: UIImage)  {
        //有的时候这里需要验证一下url是否是安全的字符
        let url = NSURL(string:  urlString)
        
        
        let cacheFilename = url!.lastPathComponent
        let cachePath = FileUtility.cachePath(cacheFilename!)
        let image: AnyObject = FileUtility.imageDataFromPath(cachePath)
        
        if image as! NSObject != NSNull() {
            self.image = image as? UIImage
        }
        else
        {
            let req = NSURLRequest(URL: url!)
            let queue = NSOperationQueue();
            NSURLConnection.sendAsynchronousRequest(req, queue: queue, completionHandler: { response, data, error in
                if (error != nil)
                {
                    dispatch_async(dispatch_get_main_queue(),
                        {
                            print(error)
                            self.image = placeHorderImage
                    })
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(),
                        {
                            
                            let image = UIImage(data: data!)
                            if (image == nil)
                            {
                                
                                print("image is nil and url fail=\(urlString)")
                                self.image = placeHorderImage
                            }
                            else
                            {
                                self.image = image
                                let bIsSuccess = FileUtility.imageCacheToPath(cachePath,image:data!)
                                if !bIsSuccess
                                {
                                    print("*******cache fail,path=\(cachePath)")
                                }
                            }
                    })
                }
            })
            
        }
        
    }
}